<template>
  <view class="prop-select">
    <view class="prop-select__title">
      <text class="prop-select__title__main">{{ title }}</text>
      <text class="prop-select__title__tip">{{ titleTip }}</text>
    </view>
    <view class="prop-select__tip">
      <text>{{ tip }}</text>
    </view>
    <view class="prop-select__box">
      <SelectBtn v-for="(item,index) in data" :key="index" :name="item.name" :selected="isSelected(item)" width="32%" @click.native="setList(item)" />
      <SelectBtn :disabled="newBtnDisabled" name="新建" width="32%" type="button" @click.native="handleClickNew" />
      <!-- 占位 -->
      <view style="height:0;width:32%"></view>
    </view>
  </view>
</template>

<script>
import SelectBtn from "./SelectBtn.vue";
export default {
  components: {
    SelectBtn
  },
  props: {
    // 是否支持多选
    multiple: {
      type: Boolean,
      default: false
    },
    title: {
      type: String,
      default: ""
    },
    tip: {
      type: String,
      default: ""
    },
    // [{ name: "甜度" }, { name: "温度" }, { name: "辣度" }]
    data: {
      type: Array,
      default: []
    }
  },
  data() {
    return {
      selectList: [],
      selectObj: { name: "" }
    };
  },
  computed: {
    titleTip() {
      return this.multiple ? "(可多选)" : "(单选)";
    },
    // 新建按钮是否不可用
    newBtnDisabled() {
      return !this.multiple && this.selectObj && this.selectObj.name
        ? true
        : false;
    }
  },
  methods: {
    setList(item) {
      if (this.multiple) {
        let index = this.selectList.findIndex(v => v.name == item.name);
        if (index > -1) {
          this.selectList.splice(index, 1); // 多选时
        } else {
          // 多选时
          this.selectList.push(item);
        }
        this.$emit("change", this.selectList);
      } else {
        // 已经选中则删除
        if (this.selectObj.name == item.name) {
          this.selectObj = {};
        } else {
          this.selectObj = item;
        }
        this.$emit("change", this.selectObj);
      }
    },
    handleClickNew() {
      if (!this.newBtnDisabled) this.$emit("new");
    },
    isSelected(item) {
      return this.multiple
        ? this.selectList.findIndex(v => v.name == item.name) > -1
        : this.selectObj.name == item.name;
    }
  }
};
</script>

<style scoped lang="scss">
.prop-select {
  .prop-select__title,
  .prop-select__tip {
    margin-bottom: 20rpx;
  }
  .prop-select__title {
    .prop-select__title__main {
      font-size: 40rpx;
      font-weight: 600;
      color: $uni-color-title;
    }
    .prop-select__title__tip {
      font-size: $uni-font-size-lg;
      color: $uni-text-color-grey;
    }
  }
  .prop-select__tip {
    font-size: $uni-font-size-lg;
    color: $uni-text-color-grey;
  }
  .prop-select__box {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    display: flex;
  }
}
</style>
